package com.zhangsun.newMvvm.common.tools;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EntityTool {

    /**
     * 实体类转Map
     *
     * @param object bean
     * @return map
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        if (object == null) {
            return map;
        }

        try {
            List<Class> classes = new ArrayList<>();
            Class clazz = object.getClass();
            classes.add(clazz);
            getAllSuperClass(classes, clazz);

            for (Class targetClass : classes) {
                Field[] fields = targetClass.getDeclaredFields();

                for (Field field : fields) {
                    if (field.isSynthetic() || "serialVersionUID".equals(field.getName())) {
                        continue;
                    }
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    Object o = field.get(object);
                    if (o != null) {
                        map.put(field.getName(), o);
                    }
                    field.setAccessible(flag);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private static void getAllSuperClass(List<Class> classes, Class clazz) {
        Class superClass = clazz.getSuperclass();
        if (superClass != null) {
            classes.add(superClass);
            getAllSuperClass(classes, superClass);
        }
    }

    /**
     * Map转实体类
     *
     * @param map    需要初始化的数据，key字段必须与实体类的成员名字一样，否则赋值为空
     * @param entity 需要转化成的实体类
     * @return bean
     */
    public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
        T t = null;
        try {
            t = entity.newInstance();
            for (Field field : entity.getDeclaredFields()) {
                if (map.containsKey(field.getName())) {
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    Object object = map.get(field.getName());
                    if (object != null && field.getType().isAssignableFrom(object.getClass())) {
                        field.set(t, object);
                    }
                    field.setAccessible(flag);
                }
            }
            return t;
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }

}
